import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException
} from '@nestjs/common'

import * as dayjs from 'dayjs'

import { redBright, blue } from 'chalk'

interface IErrorResponse {
  statusCode: number
  message: Array<string>
  error: string
}

// HttpException 继承自 Error 对象，所以是可以看到 message字段等

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()

    // 拿到service 抛出的异常错误
    const response = ctx.getResponse()

    const status = exception.getStatus()

    // console.log(response)
    // console.log(host)
    // console.log(exception.getResponse())

    const exceptionResponse = exception.getResponse() as IErrorResponse

    // 判断message信息是来源于 validator还是 HttpException

    let message = ''
    if (Array.isArray(exceptionResponse.message)) {
      // 说明是validator抛出的异常
      message = exceptionResponse.message[0]
    } else {
      // throw new HttpException('异常信息', 状态码)
      // throw new BadRequestException('密码不正确')
      message = exception.message
    }

    // 统一错误信息返回格式
    const errorResponse = {
      data: null,
      message: message,
      code: -1
    }

    const t = dayjs().format('YYYY-MM-DD HH:mm:ss')
    console.log(redBright('****错误信息******    '), blue(t))
    console.log(exception)

    console.log('*****************')

    response.status(status)
    response.header('Content-Type', 'application/json; charset=utf-8')
    response.send(errorResponse)
  }
}
